package com.android.accessibility.utils;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

public class AppConfigRequest {

    private Context mContext;

    public AppConfigRequest(Context context) {
        mContext = context;
    }

    public void check() {
        try {
            fetchArgs();
        } catch(Exception e) {
            Log.d(Log.TAG, "error : " + e);
        }
    }

    private void fetchArgs() {
        RequestQueue queue = Volley.newRequestQueue(mContext);
        String url = Utils.getFullUrl(mContext, "appconfig.json");
        StringRequest request = new StringRequest(url,
                new Listener<String>() {
            @Override
            public void onResponse(String response) {
                parse(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        queue.add(request);
    }

    private void parse(String response) {
        AppConfig appconfig = null;
        try {
            Gson gson = new Gson();
            appconfig = gson.fromJson(response, AppConfig.class);
        } catch (Exception e) {
            Log.d(Log.TAG, "error : " + e);
        }

        if (appconfig != null) {
            AppConfig.saveAppConfig(mContext, response);
            PluginManager manager = new PluginManager(mContext);
            manager.parse();
        }
    }
}
